package cn.livingCloud.controller.content;

import cn.livingCloud.dto.ArticleDto;
import cn.livingCloud.dto.ArticleFormDto;
import cn.livingCloud.dto.ArticleJsonDto;
import cn.livingCloud.dto.ArticleListDto;
import cn.livingCloud.dto.front.ArticleFrontDto;
import cn.livingCloud.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 文章列表
 * Created by DingJie  on 2016/1/15.
 */
@Controller
@RequestMapping("/admin/article")
public class ArticleController {
    private static String PREV_URL = "/article/display.htm?uuid=";

    @Autowired
    private ArticleService service;

    @RequestMapping("/list.htm")
    public String loadUI(ArticleListDto listDto, Model model) {
        service.getArticleList(listDto);
        model.addAttribute("listDto", listDto);
        model.addAttribute("prev_url", PREV_URL);
        return "article/list";
    }

    @RequestMapping("/edit.htm")
    public String edit(String uuid, Model model) {
        ArticleFormDto formDto = service.loadArticleFromDto(uuid);
        model.addAttribute("formDto", formDto);
        return "article/edit";
    }

    @RequestMapping(value = "/edit.htm", method = RequestMethod.POST)
    public String edit(@ModelAttribute("formDto") @Valid ArticleFormDto formDto, BindingResult result) {
        if (result.hasErrors()) {
            return "article/edit";
        }
        service.edit(formDto);
        return "redirect:/admin/article/list.htm?edit=success";
    }

    @RequestMapping("/change_state")
    public String changeState(String uuid, boolean publish, Model model) {
        ArticleDto articleDto = service.uploadState(uuid, publish);
        model.addAttribute("listDto", articleDto);
        return "article/list_item";
    }

    //删除
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    public String delete(String uuid) {
        service.delete(uuid);
        return "redirect:list.htm?delete=success";
    }

    @RequestMapping("/search_article")
    @ResponseBody
    public List<ArticleJsonDto> load(String key) {
        return service.searchList(key);
    }

    //文章预览
    @RequestMapping("/display.htm")
    public String load(@RequestParam String uuid, Model model) {
        ArticleFrontDto articleDto = service.getArticleFrontDto(uuid);
        model.addAttribute("articleDto", articleDto);
        return "article/display";
    }
}
